
const _registry = {};

export function emit(name, event) {
  const reg = _registry[name];
  if (reg) {
    const {listeners} = reg;
    for (let k in listeners) {
      const f = listeners[k];
      if (f) f(event);
    }
  }
}

export function subscribe(name, listener) {
  let reg = _registry[name];
  if (!reg) {
    reg = _registry[name] = {
      count: 0,
      listeners: [],
    };
  }
  reg.count ++;
  const id = reg.listeners.length;
  let removed = false;
  reg.listeners.push(listener);
  return function () {
    if (removed) {
      return;
    }
    removed = true;
    delete reg.listeners[id];
    -- reg.count;
    if (reg.count === 0) {
      delete _registry[name];
    }
  }
}
